package org.xurui.sxl.protocol.command.impl;

import org.jetlinks.core.message.DeviceMessage;
import org.jetlinks.core.message.codec.FromDeviceMessageContext;
import org.jetlinks.core.message.event.EventMessage;
import org.xurui.sxl.protocol.command.CmdCodec;
import org.xurui.sxl.protocol.enums.CommandEnum;
import org.xurui.sxl.protocol.utils.BinaryUtils;
import org.xurui.sxl.protocol.utils.NumberUtils;
import org.xurui.sxl.protocol.utils.SxlMessageUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 终端设备上传电子签到通知信息
 */
public class CmdCodec_POSTIN implements CmdCodec {
    @Override
    public boolean supportsCmd(String cmd) {
        return CommandEnum.POSTIN.name().equals(cmd);
    }

    @Override
    public boolean supportsRelayCmd() {
        return false;
    }

    @Override
    public List<DeviceMessage> parsePayload(String payload, FromDeviceMessageContext context) {
        //终端设备上传电子签到通知信息 设备上报 TODO 没有 SV,BAT
        //格式：*XX,YYYYYYYYYYYYYYY,POSTIN,HHMMSS,POSTID,S,latitude,D,longitude,G,speed,pdop,DDMMYY,track_status#
        //例子：*TJ,2020916301,POSTIN,130305,1,A,2230.7021,N,11355.1445,E,0.0,2.8,271112,FFFFFFFF#
        //回复格式：*XX,YYYYYYYYYYYYYYY,V4,POSTIN,seq,HHMMSS#
        //回复示例：*TJ,2020916301,V4,POSTIN,130305,130306#
        //参数说明：POSTID 岗位/学校组 ID
        //解析数据为事件上报
        EventMessage eventMessage = new EventMessage();
        //ReportPropertyMessage report = ReportPropertyMessage.create();
        String[] payloadArr = payload.replaceAll("\\*", "").split(",");
        String deviceId = payloadArr[1];
        eventMessage.setEvent(CommandEnum.POSTIN.name());
        eventMessage.setDeviceId(deviceId);
        eventMessage.setMessageId(deviceId + "_" + payloadArr[3]);
        eventMessage.setTimestamp(System.currentTimeMillis());
        Map<String, Object> properties = new HashMap<>();
        properties.put("postId", payloadArr[4]);
        properties.put("uptime",payloadArr[3]);
        properties.put("s",payloadArr[5]);
        properties.put("latitude",BinaryUtils.getWgs84LonLat(payloadArr[6],"lat"));
        properties.put("d",payloadArr[7]);
        properties.put("longitude",BinaryUtils.getWgs84LonLat(payloadArr[8],"lon"));
        properties.put("g",payloadArr[9]);
        properties.put("speed",NumberUtils.parseDouble(payloadArr[10]));
        properties.put("pdop",NumberUtils.parseDouble(payloadArr[11]));
        properties.put("upday",payloadArr[12]);
        String trackerStatusHex = payloadArr[13];

        Map<String,Object> trackerStatusMap = parseTrackerStatus(trackerStatusHex);
        properties.put("trackerstatus",trackerStatusMap);
        //report.setProperties(properties);
        eventMessage.setData(properties);
        //回复设备数据
        SxlMessageUtils.bulidAndSend2DeviceV4Msg(context,payloadArr[0],deviceId,CommandEnum.POSTIN.name(),payloadArr[3]);
        return genDeviceMessage(eventMessage);
    }
}
